import os
import chardet

def detect_encoding(file_path):
    """使用 chardet 检测文件编码"""
    with open(file_path, "rb") as f:
        result = chardet.detect(f.read(1024))  # 读取前1KB提高效率
    return result["encoding"]

def convert_gbk_to_utf8(file_path):
    encoding = detect_encoding(file_path)
    if not encoding:
        print(f"[警告] 无法识别编码: {file_path}")
        return
    
    # 统一编码名称（如 GBK 可能被识别为 GB2312）
    encoding = encoding.lower()
    if "gb" in encoding or "koi8" in encoding:  # 常见 GBK 变种 [[4]]
        try:
            # 以 GBK 读取并以 UTF-8 写入
            with open(file_path, "r", encoding="gbk") as f:
                content = f.read()
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(content)
            print(f"[成功] 已转换 GBK 文件: {file_path}")
        except Exception as e:
            print(f"[错误] 转换失败 {file_path}: {str(e)}")
    elif encoding == "utf-8" or encoding == "utf-8-sig":
        print(f"[跳过] 已是 UTF-8 编码: {file_path}")
    else:
        print(f"[跳过] 非目标编码 ({encoding}): {file_path}")

def batch_convert(directory):
    for root, _, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            convert_gbk_to_utf8(file_path)

if __name__ == "__main__":
    target_dir = input("请输入目标目录路径: ").strip()
    if os.path.isdir(target_dir):
        batch_convert(target_dir)
    else:
        print("[错误] 输入的不是有效目录！")